﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class PromoAnalysis : System.Web.UI.Page
{
    DataColumn cFromNo = new DataColumn("from_no", typeof(string));
    DataColumn cFromNet = new DataColumn("from_net", typeof(string));
    DataColumn cToNo = new DataColumn("to_no", typeof(string));
    DataColumn cToNet = new DataColumn("to_net", typeof(string));
    DataColumn cDate = new DataColumn("date", typeof(DateTime));
    DataColumn cTime = new DataColumn("time", typeof(double));
    DataColumn cHour = new DataColumn("hour", typeof(int));
    DataColumn cMin = new DataColumn("min", typeof(int));



    DataTable callingLog
    {
        get
        {
            if (Session["SESS_CALL_LOG_TABLE"] == null)
            {
                Session["SESS_CALL_LOG_TABLE"] = new DataTable();
                DataTable tb = Session["SESS_CALL_LOG_TABLE"] as DataTable;
                tb.TableName = "CallingLog";
                tb.Columns.Add(cFromNo);
                tb.Columns.Add(cFromNet);
                tb.Columns.Add(cToNo);
                tb.Columns.Add(cToNet);
                tb.Columns.Add(cDate);
                tb.Columns.Add(cTime);
                tb.Columns.Add(cHour);
                tb.Columns.Add(cMin);
            }

            return Session["SESS_CALL_LOG_TABLE"] as DataTable;
        }
        set
        {
            Session["SESS_CALL_LOG_TABLE"] = value;
        }
    }


    Dictionary<string, DateTime> SpecificDateTime
    {
        get
        {
            if (Session["SESS_SPEC_DATE_TIME"] == null)
            {
                Session["SESS_SPEC_DATE_TIME"] = new Dictionary<string, DateTime>();
            }
            return Session["SESS_SPEC_DATE_TIME"] as Dictionary<string, DateTime>;
        }
        set
        {
            Session["SESS_SPEC_DATE_TIME"] = value;
        }
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["SESS_CALL_LOG_TABLE"] == null)
            {
                Response.Redirect("CallLogUpload.aspx");
            }

            if (!IsPostBack)
            {

            }

            cFromNo = callingLog.Columns["from_no"];
            cFromNet = callingLog.Columns["from_net"];
            cToNo = callingLog.Columns["to_no"];
            cToNet = callingLog.Columns["to_net"];
            cDate = callingLog.Columns["date"];
            cTime = callingLog.Columns["time"];
            cHour = callingLog.Columns["hour"];
            cMin = callingLog.Columns["min"];

            AnalysLiteral();

        }
        catch
        {
        }

    }

    private void AnalysLiteral()
    {

        var callingLinq = from myRow in callingLog.AsEnumerable()
                          select new
                          {
                              CallTo = myRow.Field<string>(cToNo),
                              NetTo = myRow.Field<string>(cToNet),
                              OnDate = myRow.Field<DateTime>(cDate),
                              AtTime = myRow.Field<double>(cTime),
                              InHour = myRow.Field<int>(cHour),
                              Minutes = myRow.Field<int>(cMin),
                          };

        var topFriendRaw = (from myRow in callingLinq
                            where ((myRow.NetTo == "tmove")||
                                  (myRow.NetTo == "ais")  ||
                                  (myRow.NetTo == "dtac"))
                            group myRow by myRow.CallTo into grp
                            select new
                            {
                                CallTo = grp.Key,
                                Count = grp.Count(),
                                Sum = grp.Average(r => r.Minutes),
                                Weight = grp.Sum(r => r.Minutes),
                                NetTo = grp.Max(r => r.NetTo)
                            });

        List<DomainUsage> usage = new List<DomainUsage>();
        List<DomainUsagePro> freq = new List<DomainUsagePro>();
        //----------- ALL ---------------------------------
        DomainUsage d = 
            new DomainUsage(callingLog, 
                            ProviderEnum.All, 
                            "");
        usage.Add(d);


        //Duration
        GridView1.DataSource = GenTable(usage);
        GridView1.DataBind();


        DomainUsagePro dp = new DomainUsagePro(callingLog, ProviderEnum.All, "");
        freq.Add(dp);
        //Freq
        GridView4.DataSource = GenTablePro(freq);
        GridView4.DataBind();

        //----------- AIS ---------------------------------

        usage = new List<DomainUsage>();
        d = new DomainUsage(callingLog,
                            ProviderEnum.AIS,
                            "");
        usage.Add(d);

        freq = new List<DomainUsagePro>();
        dp = new DomainUsagePro(callingLog,
                            ProviderEnum.AIS
                            ,"");

        freq.Add(dp);
        //----------- DTAC ---------------------------------
        d = new DomainUsage(callingLog,
                            ProviderEnum.DTAC,
                            "");
        usage.Add(d);

        dp = new DomainUsagePro(callingLog,
                            ProviderEnum.DTAC
                            , "");

        freq.Add(dp);

        //----------- TMOVE ---------------------------------
        d = new DomainUsage(callingLog,
                            ProviderEnum.TMOVE,
                            "");
        usage.Add(d);

        dp = new DomainUsagePro(callingLog,
                            ProviderEnum.TMOVE
                            , "");

        freq.Add(dp);

        //Duration
        GridView2.DataSource = GenTable(usage);
        GridView2.DataBind();

        //Freq
        GridView5.DataSource = GenTablePro(freq);
        GridView5.DataBind();

        // -------- FRIENDS -----------------------------
        usage = new List<DomainUsage>();
        freq = new List<DomainUsagePro>();
        foreach(var x in topFriendRaw)
        {
            d = new DomainUsage(callingLog, ProviderEnum.All, x.CallTo);
            usage.Add(d);

            dp = new DomainUsagePro(callingLog, ProviderEnum.All, x.CallTo);
            freq.Add(dp);
        }

        //Duration
        GridView3.DataSource = GenTable(usage);
        GridView3.DataBind();

        //Freq
        GridView6.DataSource = GenTablePro(freq);
        GridView6.DataBind();

        Session["SESS_TOP_FRIENDS"] = usage;
    }


    protected void btnProcess_Click(object sender, EventArgs e)
    {
        Response.Redirect("EstimatePromotion.aspx");
    }

    DataTable GenTable(List<DomainUsage> usage)
    {
        double totalScore = 0;

        foreach (DomainUsage u in usage)
        {
            u.Analysis();
            totalScore += u.AllScore;
        }

        usage.Sort();
        usage.Reverse();

        DataTable dt = new DataTable();
        dt.Columns.Add("ID");
        dt.Columns.Add("Provider");
        //dt.Columns.Add("Start");
        //dt.Columns.Add("End");
        //dt.Columns.Add("Style");
        dt.Columns.Add("Mins");
        //dt.Columns.Add("Left", typeof(Unit));
        //dt.Columns.Add("Width", typeof(Unit));
        dt.Columns.Add("Score");
        dt.Columns.Add("Graph");

        int i = 0;

        foreach (DomainUsage u in usage)
        {
            if (++i > 10)
            {
                break;
            }

            DataRow drow = dt.NewRow();
            drow["ID"] = u.FullName;
            drow["Provider"] = u.ProviderString;
            //drow["Start"] = u.StartHour;
            //drow["End"] = u.EndHour;
            //drow["Style"] = "margin-left=" + u.StartHour * 15 + "px; width:" + (u.EndHour - u.StartHour) * 15 + "px; color=red";
            //double mins = Math.Round(u.MaxValue / u.TotalMonths, 2);//.ToString("#,##0.00");
            //DateTime d = new DateTime(2011, 1, 1, 0, 0, 0);
            //d =d.AddMinutes(mins);
            //drow["Mins"] = d.ToString("h.mm");
            double min = Math.Round(u.ThisScore * 100.0 / totalScore, 2);
            drow["Mins"] = min.ToString("#,##0.00") + " %";
            //drow["Left"] = new Unit((u.StartHour + 1) * 15 - 6, UnitType.Pixel);
            //drow["Width"] = new Unit(((u.EndHour < u.StartHour ? (u.EndHour + 24) : u.EndHour) - u.StartHour) * 15, UnitType.Pixel);
            drow["Score"] = u.MaxPercent;
            drow["Graph"] = getLiteral(u.HourBoolean);

            if (min > 0)
            {
                dt.Rows.Add(drow);
            }
        }

        return dt;
    }

    string getLiteral(bool[] hourBool)
    {
        string lit = "<img src='images/blank.gif' class='imagestart' />";

        foreach (bool h in hourBool)
        {
            lit += h ? "<img src='images/rate.jpg' class='imagerate' />" : "<img src='images/blank.gif' class='imageblank' />";
        }

        return lit;
    }

    DataTable GenTablePro(List<DomainUsagePro> usage)
    {
        double totalScore = 0;

        foreach (DomainUsagePro u in usage)
        {
            u.Analysis();
            totalScore += u.AllScore;
        }

        usage.Sort();
        usage.Reverse();

        DataTable dt = new DataTable();
        dt.Columns.Add("ID");
        dt.Columns.Add("Provider");
        //dt.Columns.Add("Start");
        //dt.Columns.Add("End");
        //dt.Columns.Add("Style");
        dt.Columns.Add("Mins");
        //dt.Columns.Add("Left", typeof(Unit));
        //dt.Columns.Add("Width", typeof(Unit));
        dt.Columns.Add("Score");
        dt.Columns.Add("Graph");

        int i = 0;

        foreach (DomainUsagePro u in usage)
        {
            if (++i > 10)
            {
                break;
            }

            DataRow drow = dt.NewRow();
            drow["ID"] = u.FullName;
            drow["Provider"] = u.ProviderString;
            //drow["Start"] = u.StartHour;
            //drow["End"] = u.EndHour;
            //drow["Style"] = "margin-left=" + u.StartHour * 15 + "px; width:" + ((u.EndHour - u.StartHour) * 15 -4) + "px; color=red";
            //drow["Mins"] = Math.Round(u.MaxValue / u.TotalMonths, 2).ToString("#,##0.00");
            double min = Math.Round(u.ThisScore * 100.0 / totalScore, 2);
            drow["Mins"] = min.ToString("#,##0.00") + " %";
            //drow["Left"] = new Unit((u.StartHour + 1) * 15 - 6, UnitType.Pixel);
            //drow["Width"] = new Unit(((u.EndHour < u.StartHour ? (u.EndHour + 24) : u.EndHour) - u.StartHour) * 15 , UnitType.Pixel);
            drow["Score"] = u.MaxValue;
            drow["Graph"] = getLiteral(u.HourBoolean);

            if (min > 0)
            {
                dt.Rows.Add(drow);
            }
        }

        return dt;
    }
}


